package com.gomcarter.frameworks.base.common;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class ZipUtils {

    /**
     * @param zipFileName zipFileName
     * @param inputFile   inputFile
     * @throws Exception for failed
     */
    private static void zip(String zipFileName, File inputFile) throws Exception {
        try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
             BufferedOutputStream bo = new BufferedOutputStream(out)) {
            zip(out, inputFile, inputFile.getName(), bo);
        }
    }

    /**
     * @param out       ZipOutputStream out
     * @param inputFile inputFile
     * @throws Exception for failed
     */
    private static void zip(ZipOutputStream out, File inputFile) throws Exception {
        try (BufferedOutputStream bo = new BufferedOutputStream(out)) {
            zip(out, inputFile, inputFile.getName(), bo);
        }
    }

    /**
     * 方法重载
     *
     * @param out  out
     * @param file file
     * @param base base
     * @param bo   bo
     * @throws Exception for failed
     */
    private static void zip(ZipOutputStream out, File file, String base,
                            BufferedOutputStream bo) throws Exception {
        if (file.isDirectory()) {
            File[] fl = file.listFiles();
            if (fl != null) {
                if (fl.length == 0) {
                    // 创建zip压缩进入点base
                    out.putNextEntry(new ZipEntry(base + "/"));
                }
                for (File value : fl) {
                    // 递归遍历子文件夹
                    zip(out, value, base + "/" + value.getName(), bo);
                }
            }
        } else {
            // 创建zip压缩进入点base
            out.putNextEntry(new ZipEntry(base));
            try (FileInputStream in = new FileInputStream(file);
                 BufferedInputStream bi = new BufferedInputStream(in)) {
                int b;
                while ((b = bi.read()) != -1) {
                    // 将字节流写入当前zip目录
                    bo.write(b);
                }
            }
        }
    }
}
